package fnsvr

import (
	"io"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type OssConfig struct {
	Endpoint        string `xml:"endpoint"` //https://oss-cn-chengdu.aliyuncs.com
	AccessKeyID     string `xml:"accessKeyID"`
	AccessKeySecret string `xml:"accessKeySecret"`
	BucketName      string `xml:"bucketName"`
}

func NewOssClient(cfg *OssConfig) (*oss.Client, error) {
	return oss.New(cfg.Endpoint, cfg.AccessKeyID, cfg.AccessKeySecret)
}

// 上传数据到oss
func UploadToOSS(client *oss.Client, bucketName string, data io.Reader, objectPath string) error {

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return err
	}

	err = bucket.PutObject(objectPath, data)
	if err != nil {
		return err
	}

	return nil
}

// 从oss下载数据
func DownloadFromOSS(client *oss.Client, bucketName string, objectPath string) ([]byte, error) {

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return nil, err
	}

	// 获取文件对象
	obj, err := bucket.GetObject(objectPath)
	if err != nil {
		return nil, err
	}
	defer obj.Close()

	// 读取文件内容
	data, err := io.ReadAll(obj)
	if err != nil {
		return nil, err
	}

	return data, nil
}
